package com.ssm.common.listener;


import java.util.HashSet;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 *  监听在线人数
 */
@WebListener
public class SessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext context = session.getServletContext();
        //  用set集合来存储session对象
        HashSet<HttpSession> sessionSet = (HashSet<HttpSession>) context.getAttribute("sessionSet");
        if(sessionSet == null){
            sessionSet = new HashSet<HttpSession>();
            context.setAttribute("sessionSet", sessionSet);
        }
        sessionSet.add(session);

        // 记录在线人数
        context.setAttribute("onlineCount", sessionSet.size());
    }

    //session的销毁监听
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext context = event.getSession().getServletContext();
        if (context.getAttribute("onlineCount") == null) {
            context.setAttribute("onlineCount", 0);
        } else {
            int onlineCount = (Integer) context.getAttribute("onlineCount");
            if (onlineCount < 1) {
                onlineCount = 1;
            }
            context.setAttribute("onlineCount", onlineCount - 1);
        }
        HttpSession session = event.getSession();
        HashSet<HttpSession> sessionSet = (HashSet<HttpSession>)context.getAttribute("sessionSet");
        if(sessionSet!=null){
            sessionSet.remove(session);
        }
    }

}
